package cn.virens.common.easyexcel.dict;

import cn.idev.excel.metadata.data.ReadCellData;
import cn.virens.common.util.exception.APIException;
import org.dromara.hutool.core.collection.CollUtil;
import org.dromara.hutool.core.convert.ConvertUtil;
import org.dromara.hutool.core.map.BiMap;

import java.util.HashMap;
import java.util.List;

@SuppressWarnings("serial")
public class ExcelDict extends BiMap<String, Object> {
    private AbstractExcelDictConverter<?> converter;

    private final List<String> headNames;

    public ExcelDict(List<String> headNames) {
        super(new HashMap<>());

        this.headNames = headNames;
    }

    /**
     * 设置对应转换器类型
     */
    protected void setConverter(AbstractExcelDictConverter<?> converter) throws APIException {
        this.converter = converter;
    }

    /**
     * 获取对应的转换器实例
     */
    protected AbstractExcelDictConverter<?> getConverter() throws APIException {
        return converter;
    }

    public Object getValue(ReadCellData<?> cellData) throws APIException {
        return get(cellData.getStringValue());
    }

    /**
     * 获取对应的转换器类型
     */
    protected Class<?> getConverterClass() throws APIException {
        return converter.getClass();
    }

    /**
     * 获取对应的值类型
     */
    protected Class<?> getValueClass() throws APIException {
        return converter.supportJavaTypeKey();
    }

    /**
     * 是否包含指定的行头
     */
    public boolean includeHeadName(String hm) throws APIException {
        return CollUtil.contains(headNames, l -> l.equals(hm));
    }

    public String[] getKeyArray() throws APIException {
        return keySet().toArray(number -> {
            return new String[size()];
        });
    }

    /**
     * 将任意数值转为需要的值类型
     */
    public Object toValue(Object obj) throws APIException {
        return ConvertUtil.convert(getValueClass(), obj);
    }
}
